package com.blb.socket.demo1;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端
 */
public class MyServer {

    public static final int PORT = 8888;

    /**
     * 启动
     */
    public void start(){
        System.out.println("服务器启动了");
        //创建ServerSocket
        try (ServerSocket serverSocket = new ServerSocket(PORT)){
            while(true){
                //循环获得客户端
                Socket client = serverSocket.accept();
                System.out.println(client.getInetAddress()+"连接了！");
                //读取客户端的消息  BufferedReader，ObjectInputStream，DataInputStream
                try(ObjectInputStream ois = new ObjectInputStream(client.getInputStream())) {
                    String msg = ois.readUTF();
                    System.out.println(client.getInetAddress() + "说：" + msg);
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MyServer().start();
    }
}
